package com.shuguoyiyou.wechatofficialaccount.controller;

import com.shuguoyiyou.wechatofficialaccount.service.impl.IMpUserInfoService;
import com.springboot.cloud.common.core.entity.vo.Result;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@AllArgsConstructor
@RestController
@RequestMapping("/wechatOfficialAccount")
public class MpUserInfoController {

//	private final WxMpService wxMpService;
//
//	@Autowired
//	private RedisService redisService;

    @Autowired
    private IMpUserInfoService iWxMpUserInfoService;

//	@Autowired
//	private ResourceProvider resourceProvider;
//
//	@Autowired
//	private WeiXinService weiXinService;
//	@Autowired
//	private WeiXinConfig weiXinConfig;

    /**
     * 获取微信用户信息
     *
     * @param code
     * @param request
     * @param response
     * @param session
     * @return
     * @throws IOException
     */
    // 获取openid
    @RequestMapping("/getWeiXinUserInfoByUsernameValue/{username}/{value}")
    public String getWeiXinUserInfoByUsernameValue(String code, @PathVariable String username, @PathVariable String value, HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IOException, WxErrorException {
        System.out.println("usernameusername:" + username);
        System.out.println("valueaaa:" + value);
        return iWxMpUserInfoService.getWeiXinUserInfoByUsernameValue(code, username, value, request, response, session);
    }

    // 二维码
    @ApiOperation(value = "获取云回复", notes = "获取指定云回复信息")
    @GetMapping(value = "/code")
    public Result get() {
        String png_base64 = iWxMpUserInfoService.getCode();
        return Result.success(png_base64);
    }
    /**
     * 获取微信用户信息
     * @param code
     * @param request
     * @param response
     * @param session
     * @return
     * @throws IOException
     */
    // 获取openid
//	@RequestMapping("/getWeiXinUserInfo/{username}")
//	public String getWeiXinUserInfo(String code, @PathVariable String username, HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IOException, WxErrorException {
//		//第一步：用户同意授权，获取code
////		String uid="123";
//		System.out.println("code1:"+code);
//		if (code == null) {
//			String url = URLEncoder.encode(request.getRequestURL().toString());
//			System.out.println("url:"+url);
//			String authorizeUrl = weiXinService.buildAuthorizeURL(url);
//			System.out.println("authorizeUrl:"+authorizeUrl);
//			response.sendRedirect(authorizeUrl);
//			return null;
//		}
//		//第二步：通过code换取网页授权access_token
//		String htmlInfo = "";
//		System.out.println("code:"+code);
//		Map<String, Object> accesstokenInfo = weiXinService.getACCESSTOKEN(code);
//		System.out.println("accesstokenInfo:"+accesstokenInfo);
//		String errcode = (String)accesstokenInfo.get("errcode");
//		System.out.println("errcode:"+errcode);
//		if(StringUtils.isEmpty(errcode)){
//			//第四步：拉取用户信息(需scope为 snsapi_userinfo)
//			Map<String, Object> weiXinUserInfo = weiXinService.getWeiXinUserInfo(accesstokenInfo);
//			System.out.println("weiXinUserInfo:"+weiXinUserInfo);
//			String userInfohtml = createUserInfoHtml(weiXinUserInfo, username);
//			System.out.println("userInfohtml:"+userInfohtml);
//			return userInfohtml;
//		}
//		return htmlInfo;
//	}


    /**
     * 获取微信用户信息
     * @param code
     * @param request
     * @param response
     * @param session
     * @return
     * @throws IOException
     */
    // 获取openid
//	@RequestMapping("/getWeiXinUserInfo")
//	public String getWeiXinUserInfo(String code, HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IOException{
//		//第一步：用户同意授权，获取code
//		System.out.println("code1:"+code);
//		if (code == null) {
//			String url = URLEncoder.encode(request.getRequestURL().toString());
//			System.out.println("url:"+url);
//			String authorizeUrl = weiXinService.buildAuthorizeURL(url);
//			System.out.println("authorizeUrl:"+authorizeUrl);
//			response.sendRedirect(authorizeUrl);
//			return null;
//		}
//		//第二步：通过code换取网页授权access_token
//		String htmlInfo = "";
//		System.out.println("code:"+code);
//		Map<String, Object> accesstokenInfo = weiXinService.getACCESSTOKEN(code);
//		System.out.println("accesstokenInfo:"+accesstokenInfo);
//		String errcode = (String)accesstokenInfo.get("errcode");
//		System.out.println("errcode:"+errcode);
//		if(StringUtils.isEmpty(errcode)){
//			//第四步：拉取用户信息(需scope为 snsapi_userinfo)
//			Map<String, Object> weiXinUserInfo = weiXinService.getWeiXinUserInfo(accesstokenInfo);
//			System.out.println("weiXinUserInfo:"+weiXinUserInfo);
//			String userInfohtml = createUserInfoHtml(weiXinUserInfo);
//			System.out.println("userInfohtml:"+userInfohtml);
//			return userInfohtml;
//		}
//		return htmlInfo;
//	}

//	// 二维码
//	@ApiOperation(value = "获取云回复", notes = "获取指定云回复信息")
//	@GetMapping(value = "/code")
//	public Result get(HttpServletResponse response) {
//		BufferedImage image = null;
//		String png_base64 = null;
//		// 获取当前的用户
//		MyMetaObjectHandler myMetaObjectHandler=new MyMetaObjectHandler();
//		String username = myMetaObjectHandler.getCurrentUsername();
//
////		String requestUrl = "http://www.coolbreeze.top:80/wechatOfficialAccount/getWeiXinUserInfo/"+username;
//
//		Long currentTime=new Date().getTime();
//		System.out.println("currentTime:"+currentTime);
//
//		String value=currentTime+RandomStringUtils.randomAlphanumeric(6);
//		redisService.set(username,value);
//		redisService.expire(username,60);
//		String requestUrl = "http://www.coolbreeze.top:80/wechatOfficialAccount/getWeiXinUserInfoByUsernameValue/"+username+"/"+value;
//
//		System.out.println("requestUrl"+requestUrl);
//		try {
//			ByteArrayOutputStream os =new ByteArrayOutputStream();
////					OutputStream os =response.getOutputStream();
//			QrCodeUtil.encode(requestUrl, null, os);
//			byte[] bytes =  os.toByteArray();//转换成字节
//			BASE64Encoder encoder = new BASE64Encoder();
//			String png_base = encoder.encodeBuffer(bytes).trim();//转换成base64串
////			png_base64 = png_base;
//			png_base64 = png_base.replaceAll("\n", "").replaceAll("\r", "");
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//return Result.success(png_base64);
//	}

    /**
     * 生成微信用户信息Html
     * @param weiXinUserInfo
     * @return
     */
//	private String createUserInfoHtml(Map<String, Object> weiXinUserInfo,String username) throws WxErrorException {
//		String wxOpenId = (String)weiXinUserInfo.get("openid");
//		String nickname = (String)weiXinUserInfo.get("nickname");
//		String subscribe=(String)weiXinUserInfo.get("subscribe");
//		Double sex = (Double)weiXinUserInfo.get("sex");
//		String country=(String)weiXinUserInfo.get("country");
//		String sexString = "";
//		if(sex == 1.0d){
//			sexString = "男";
//		}else{
//			sexString = "女";
//		}
//		/*String province = (String)weiXinUserInfo.get("province");
//		String city = (String)weiXinUserInfo.get("city");
//		String country = (String)weiXinUserInfo.get("country");*/
//		String headimgurl = (String)weiXinUserInfo.get("headimgurl");
//		WxMpUser wxMpUser=this.wxMpService.getUserService().userInfo(wxOpenId);
//		String htmlInfo="<!DOCTYPE html>"+
//		"<html lang='en'>"+
//		  "<head>"+
//		   	"  <meta charset='UTF-8'>"+
//		   	"  <meta name='viewport' content='initial-scale=1, maximum-scale=3, minimum-scale=1, user-scalable=no'>"+
//		  "</head>"+
//		  "<body>"+
//				"<h3>绑定系统账号成功</h3>"+
//
//				"</body>"+
//				"</html>"+
//				"<script type=\"text/javascript\">\n" +
//				"    // 关闭网站\n" +
//				"    // alert(typeof(WeixinJSBridge)); 输出undifined\n" +
//				"    setTimeout(function(){\n" +
//				"        // 原生浏览器\n" +
//				"        window.close();\n" +
//				"        \n" +
//				"        // 微信浏览器\n" +
//				"        document.addEventListener('WeixinJSBridgeReady', function(){\n" +
//				"            WeixinJSBridge.invoke('closeWindow',{},function(res){});\n" +
//				"        }, false);\n" +
//				"        WeixinJSBridge.invoke('closeWindow',{},function(res){});\n" +
//				"    }, 3000);\n" +
//				"</script>";
//
//		UserOpenIdForm userOpenIdForm=new UserOpenIdForm();
//		userOpenIdForm.setUsername(username);
//		userOpenIdForm.setOpenId(wxOpenId);
//		System.out.println("username:"+username+":wxOpenId:"+wxOpenId);
//		resourceProvider.updateOpenId(userOpenIdForm);
//		return htmlInfo;
//	}

    /**
     * 生成微信用户信息Html
     * @param weiXinUserInfo
     * @return
     */
//	private String createUserInfoHtml(Map<String, Object> weiXinUserInfo) {
//		String wxOpenId = (String)weiXinUserInfo.get("openid");
//		String nickname = (String)weiXinUserInfo.get("nickname");
//		String subscribe=(String)weiXinUserInfo.get("subscribe");
//		Double sex = (Double)weiXinUserInfo.get("sex");
//		String country=(String)weiXinUserInfo.get("country");
//		String sexString = "";
//		if(sex == 1.0d){
//			sexString = "男";
//		}else{
//			sexString = "女";
//		}
//		/*String province = (String)weiXinUserInfo.get("province");
//		String city = (String)weiXinUserInfo.get("city");
//		String country = (String)weiXinUserInfo.get("country");*/
//		String headimgurl = (String)weiXinUserInfo.get("headimgurl");
//
//		String htmlInfo="<!DOCTYPE html>"+
//				"<html lang='en'>"+
//				"<head>"+
//				"  <meta charset='UTF-8'>"+
//				"  <meta name='viewport' content='initial-scale=1, maximum-scale=3, minimum-scale=1, user-scalable=no'>"+
//				"</head>"+
//				"<body>"+
//				"<h3>系统登陆成功</h3>"+
//				"<p>"+wxOpenId+"</p>"+
//				"<h3>是否关注</h3>"+
//				"<p>"+subscribe+"</p>"+
//				"<h3>普通用户昵称</h3>"+
//				"<p>"+nickname+"</p>"+
//				"<h3>用户性别</h3>"+
//				"<p>"+sexString+"</p>"+
//				"<h3>国家</h3>"+
//				"<p>"+country+"</p>"+
//				"<h3>用户头像</h3>"+
//				"<img src=\""+headimgurl+"\"></img>"+
//		  	"<h3>用户openId</h3>"+
//		  	"<p>"+wxOpenId+"</p>"+
//
//		  	"<h3>普通用户昵称</h3>"+
//		  	"<p>"+nickname+"</p>"+
//		  	"<h3>用户性别</h3>"+
//		  	"<p>"+sexString+"</p>"+
//				"<h3>国家</h3>"+
//				"<p>"+country+"</p>"+
//		  	"<h3>用户头像</h3>"+
//		  	"<img src=\""+headimgurl+"\"></img>"+
//				"</body>"+
//				"</html>"+
//				"<script type=\"text/javascript\">\n" +
//				"    // 关闭网站\n" +
//				"    // alert(typeof(WeixinJSBridge)); 输出undifined\n" +
//				"    setTimeout(function(){\n" +
//				"        // 原生浏览器\n" +
//				"        window.close();\n" +
//				"        \n" +
//				"        // 微信浏览器\n" +
//				"        document.addEventListener('WeixinJSBridgeReady', function(){\n" +
//				"            WeixinJSBridge.invoke('closeWindow',{},function(res){});\n" +
//				"        }, false);\n" +
//				"        WeixinJSBridge.invoke('closeWindow',{},function(res){});\n" +
//				"    }, 3000);\n" +
//				"</script>";
//
//		return htmlInfo;
//	}

    /**
     * 初始化微信JSSDK配置信息
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
//	@RequestMapping("/initWXJSSDKConfigInfo")
//	public String initWXJSConfig (HttpServletRequest request, HttpServletResponse response) throws Exception{
//		String shareUrl = request.getParameter("shareUrl");//分享的URL
//		Map map = weiXinService.initJSSDKConfigInfo(shareUrl);
//		String json = weiXinService.mapToJson(map);
//		return json;
//	}


//	@PostMapping
//	protected void toVatifyTokenPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException  {
//		//防止进行post提交和响应的消息乱码
//		request.setCharacterEncoding("UTF-8");
//		response.setHeader("Content-type", "text/html;charset=UTF-8");
//		response.setCharacterEncoding("UTF-8");
//		PrintWriter out = response.getWriter();
//		try{
//
//			//将发送过来的消息XML形式转为map内容
//			Map<String , String> map = MessageUtils.xmlToMap(request);
//
//			String fromUserName = map.get("FromUserName");
//
//			String toUserName = map.get("ToUserName");
//			String msgType = map.get("MsgType");
//			String content = map.get("Content");
//			String message = null ;
//			if(MessageUtils.MESSAGE_EVENT.equals(msgType)){
//				String eventType = map.get("Event");
//				//订阅事件 或 未关注扫描二维码事件
//				if(MessageUtils.MESSAGE_SUBSCRIBE .equals(eventType)){
//					message = meUtils.initText(fromUserName,toUserName , MessageUtils.menuText());
//				}else if(MessageUtils.MESSAGE_SCANCODE .equals(eventType)) {
//					//进行的是扫码事件
//					String key = map.get("EventKey");
//					message = meUtils.initText(fromUserName,toUserName , "已验证信息，请稍后。");
//					User selUser= weChatServiceImpl.selUserByOpenid(fromUserName);
//					System.out.println(key);
//					ServletContext application = request.getSession().getServletContext();
//					application.setAttribute(key,selUser);
//				}else if(MessageUtils.MESSAGE_UNSUBSCRIBE .equals(eventType)) {
//					//进行的是取消关注事件
//					weChatServiceImpl.delUserOpenid(fromUserName);
//				}
//			}else {
//				message = meUtils.initText(fromUserName,toUserName , "自动回复：测试服务器，功能未完善。");
//			}
//
//			out.print(message);
//		}catch (Exception e){
//			e.printStackTrace();
//		}finally {
//			out.close();
//		}
//
//	}

}
